<?php

use com\gdl\newagk\interfaces\PaperServiceIf;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\newagk\dataobject\paper\PaperResultDTO;
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use TencentYoutuyun\YouTu;
use FaceVisaYun\FaceVisa;
use TencentYoutuyun\Conf;
use TencentYoutuyun\Auth;
date_default_timezone_set('PRC');
class api_PaperService extends api_Abstract implements PaperServiceIf
{
	
	/*****************模拟考试********************/
	//模拟考试列表
	public function mockExam(PaperResultDTO $Paper)
    {
        $resultDO = new ResultDO();

		$identity_id = $Paper->identity_id;
		$pagesize = $Paper->num;
		$page = $Paper->filename['page'];
		$platformId = $Paper->id;

	 try {
		
		$page = ($page-1) * $pagesize;
		$items = 'id,name,dbs,ques_name,duration,totalScore,passScore,totalNum,paperType,settings,updateTime';
        $groupBy = ' order by id desc  limit '.$page.','.$pagesize;
		 
		$examsession = new model_newagk_examsession();
		$platform = new model_newagk_platform();
		$papers = new model_newagk_paper();
		$archivesmark = new model_newagk_archivesmark();
		$drawquest = new service_drawquestion();
		//$admin_reg = $platform->getChildAdminRegByPlaformId($platformId);
		$condition = "status=1 and (puse=1 or puse=3) and isdelete=0"; // and admin_reg in('".implode("','",$admin_reg)."')
		if(!empty($Paper->filename['title'])){
			$condition .= " and name like '%".$Paper->filename['title']."%'";
		}


		if(!empty($Paper->filename['labeid'])){
			$labeid = explode(',',$Paper->filename['labeid']);
			foreach($labeid as $v){
				$condition .= " and labelId like '%".$v."%'";
			}
		}

		$sessionvars = $examsession->selectOne('sign=2 and identity_id='.$identity_id,'starttime,time,paperid,papername');
		$list = $papers->select($condition, $items, $groupBy)->items;
	//	$num = $paper->selectOne($condition, 'count(*) num');
		$mocklist = [];

		$paperid = empty($sessionvars['paperid']) ? 0 : $sessionvars['paperid'];
		$datime = date('Y-m-d');
		$datimes = date('Y-m-d H:i:s');
		foreach($list as $v){
			/****暂时每次都统计 等稳定后再启用每日更新一次操作****/
			
				
				//if(substr($v['updateTime'],0,10)!=$datime){
				//$v['totalNum'] = $drawquest->totalNum($v['settings']);
				$totalNum = $drawquest->totalNum($v['settings']);
				if($totalNum!=$v['totalNum']){
					$v['totalNum'] = $totalNum;
					$papers->update(['id'=>$v['id']],'totalNum='.$v['totalNum'].",updateTime='{$datimes}'");
				}
	
			$mocklist[] = [
							'id'		=>$v['id'],
							'title'		=>htmlspecialchars_decode($v['name']),
							'qName'		=>$v['ques_name'],
							'qId'		=>$v['dbs'],
							'duration'	=>(int)$v['duration'],
							'totalScore'=>$v['totalScore'],
							'passScore'	=>$v['passScore'],
							'totalNum'	=>$v['totalNum'],
							'conExam'	=>$paperid==$v['id'] ? 1 : 0,
							'starttime' =>0,//占位的没有实际意义
							'examType'	=>0, //0常规考场，1补考考场
							'startType' =>0,
							'timeLeft'  =>0,
							];
		}
		

			$resultDO->success = true;
			$contExam = ['id'=>0,'prompt'=>0,'title'=>''];
			if(!empty($sessionvars)){
				$contExam = ['id'=>$sessionvars['paperid'],'prompt'=>1,'title'=>$sessionvars['papername']];
			}
            if ($list){
				$resultDO->data = $mocklist;
				
				$resultDO->code = 1;
            }else{
               $resultDO->code = 0;
            }
			$resultDO->message = json_encode($contExam);
    
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }
	//模拟考试筛选标签
	public function filterList(PaperResultDTO $Paper)
    {
        $resultDO = new ResultDO();

		$identity_id = $Paper->identity_id;
		$platformId = $Paper->id;
	 try {
		$labels = new model_newagk_labels();
		$platform = new model_newagk_platform();
		$paper = new model_newagk_paper();
		$admin_reg = $platform->getChildAdminRegByPlaformId($platformId);
		$chooseid = $paper->getInfoArgLabels(1);
		$paperid = [0];
		foreach($chooseid as $k=>$v){
				$paperid[] = $k;
		}
		$labelist = $labels->getInfoArgDetails(implode(',',$paperid));
		$datas = ['tagList'=>[]];
					
		$data = [];
		foreach($labelist as $v){
			$data['id'] = $v["title"]["name"];
			$data['pid'][] = [['id'=>'0','tagName'=>'全部']];
			foreach($v["list"] as $vl){
				$data['pid'][] = ['id'=>$vl['id'],'tagName'=>$vl['name']];
			}
			$datas['tagList'][] = $data;
			$data = [];
		}
		
			$resultDO->success = true;
			$resultDO->code = 1;
           
			$resultDO->message = json_encode($datas);
    
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }
	
	
	//生成试卷
	public function generate(PaperResultDTO $basic)
    {
		$result = new ResultDO();
		$id = $basic->id ? gdl_lib_BaseUtils::getStr($basic->id,'int') : 0;
		$platform_id = $basic->platform_id ? gdl_lib_BaseUtils::getStr($basic->platform_id,'int') : 0;
		$basicid = $basic->basicid ? gdl_lib_BaseUtils::getStr($basic->basicid,'int') : 0;
		$identity_id = $basic->identity_id ? gdl_lib_BaseUtils::getStr($basic->identity_id,'int') : 0;
		if(!$id || !$platform_id || !$identity_id){
			$result->code = 0;
			$result->message = '缺少必要参数';
			$result->success = true;
            return $result;
			
		}
	try {
		

			$paper = new model_newagk_paper();
			$basic = new model_newagk_basic();
			$qbank = new model_newagk_qbank();
			$examsession = new model_newagk_examsession();
			$basicuser = new model_newagk_basicuser();
			$globald = new service_globals();
			if($basicid){
				//表示生成的是正式试卷
				$basicDel = $basic->selectOne(['id'=>$basicid,'status'=>1,'isdelete'=>'0'], 'pid,starttime');
				$basicuserDel = $basicuser->selectOne(['basic_id'=>$basicid,'identity_id'=>$identity_id], 'id');
				if(empty($basicDel) || empty($basicuserDel)){
					$result->code = 0;
					$result->message = '考场不存在';
					$result->success = true;
					return $result;
				}
				if(strtotime($basicDel['starttime'])>time()){
					$result->code = 0;
					$result->message = '考试未开始';
					$result->success = true;
					return $result;
				}
				
				$id=$basicDel['pid'];
			}
			
			
			$paperArr = $paper->selectOne(['id'=>$id],'dbs,paperType,datas,settings,duration,totalScore,passScore,name,id,ques_name');
			if($paperArr['paperType']==2){

				$result->data[][] = 1;
				$msg = unserialize($paperArr['datas']);

			} else {
				$drawquestion = new service_drawquestion();
				$result->data[][] = 2;
				$msg = $drawquestion->randomDrawQues($paperArr['dbs'],$paperArr['settings'],1);
			}	

				
			if(empty($msg)){
				$result->code = 0;
				$result->message = '配置错误';
				$result->success = true;
				return $result;
			}
				$data = [];

				foreach($msg as $k=>$v){
					foreach($v as $kg=>$vg){
						//对答案进行处理

						$data[$k][] = [
										'id'=>$vg['id'],
										'typeId'=>$vg['typeId'],
										'question'=>$vg['question'],
										'select'=>$vg['select'],
										'q_select_arr'=>$vg['q_select_arr'],
										'questionImg'=>$vg['questionImg'],
										'qbankId'=>$vg['qbankId'],
										'finalAnswer'=>'',
										'answer'=>$vg['answer'],
										'sectionId'=>$vg['sectionId'],
										'describe'=>$vg['describe'],
										];
					}
				}


				$settings= ['qbankId'=>$paperArr['dbs'],'list'=>$data,'qbankName'=>$paperArr['ques_name'],'duration'=>$paperArr['duration'],'totalScore'=>$paperArr['totalScore'],'passScore'=>$paperArr['passScore'],'paperName'=>$paperArr['name'],'id'=>$paperArr['id'],'setting'=>$paperArr['settings']];
				

				$sessionid = $examsession->addExamHistory($identity_id,$settings,$basicid);
                if ($sessionid) {

                    $result->code = 1;

                } else {
                    $result->code = 0;
					$result->message = '生成试卷失败';
                }
	
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = 0;
                $result->message = '异常';
            }
            return $result;
	}
	
	//进入考场
	public function enterExam(PaperResultDTO $basic)
    {
		$result = new ResultDO();

		$platform_id = $basic->platform_id ? gdl_lib_BaseUtils::getStr($basic->platform_id,'int') : 0;
		$identity_id = $basic->identity_id ? gdl_lib_BaseUtils::getStr($basic->identity_id,'int') : 0;
		$status = $basic->status ? gdl_lib_BaseUtils::getStr($basic->status,'int') : 3;
		$basicid = $basic->basicid ? gdl_lib_BaseUtils::getStr($basic->basicid,'int') : 0;
		if(!$platform_id || !$identity_id){
			$result->code = 0;
			$result->message = '缺少必要参数';
			$result->success = true;
            return $result;
			
		}
	try {
			$examsession = new model_newagk_examsession();
			$papers = new model_newagk_paper();
			$collection = new model_newagk_collection();
			$qbank = new model_newagk_qbank();
			
			
			$paperArr = $examsession->getListByArgOne(['sign'=>$status,'identity_id'=>$identity_id,'basicid'=>$basicid],'starttime,time,es_useranswer,question,papername,setting,paperid');
			$qId = $papers->selectOne(['id'=>$paperArr['paperid']],'dbs');

			$collect = $collection->cllKeep($identity_id,$qId['dbs']);
			//$logo = $qbank->getListByArgNamefield(0);
			if(empty($paperArr)){
				$result->code = 0;
				$result->message = '考试不存在';
				$result->success = true;
				return $result;
			
			}
						
					
			
			$newest = 0;
			$datas=[];
			$sheet=[];
			$record=['done'=>0,'notDone'=>0,'unknown'=>0];
			$Remtime = ($paperArr['starttime']+$paperArr['time'])-time();
			$question = unserialize($paperArr['question']);
			$answer = unserialize($paperArr['es_useranswer']);
			$i=1;
			foreach($question as  $k=>$v){
				
				foreach($v as  $kq=>$vq){
					$vq['finalAnswer'] = empty($answer[$vq['id']]) ? '' : $answer[$vq['id']];
					$vq['iscollection'] = in_array($vq['id'],$collect) ? 1 : 0;
				//	$vq['questionImg'] = empty($logo[$vq['qbankId']]['thumb']) ? '' : $logo[$vq['qbankId']]['thumb'];
					if(empty($answer[$vq['id']])){
						
						$selected =0;//未做
						$record['notDone']+=1;
					} else {
						$newest = $vq['id'];
						if($vq['typeId']<4){
							$selected =1;//已做
							$record['done']+=1;
						} else {
							$selected =2;//未知
							$record['unknown']+=1;
						}
					}
					//将用户答案丢到题里面去
				
				$datas[$k][] = $vq;
			
				if(!empty($sheet[$k]['key']) && $sheet[$k]['key']==$k){
					$sheet[$k]['list'][] = ['id'=>$i,'qid'=>$vq['id'],'selected'=>$selected];
				} else {
					$sheet[$k] = ['key'=>$k,'list'=>[['id'=>$i,'qid'=>$vq['id'],'selected'=>$selected]]]; 
				}
				
				//$sheet[$k][] = ['id'=>$i,'selected'=>$selected];
				//答题卡
					$i++;
				}
			}

			if(!empty($sheet)){
				$sheet = array_values($sheet);
			}
				$setting = unserialize($paperArr['setting']);
				$data = [
						'remtime'=>$Remtime>0 ? $Remtime : 0, //剩余时间
						'papername'=>$paperArr['papername'],
						'list'=>$datas,
						'deregulationNum'=>3,//违规操作次数
						//'list'=>[1],
						'sheet'=>$sheet,
						'record'=>$record,
						'newest'=>$newest,
						'qbankId'=>$qId['dbs'],
						];

	
                if (!empty($data['list'])) {
					$result->message = json_encode($data);
                    $result->code = 1;

                } else {
                    $result->code = 0;
					$result->message = 0;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
	}
	
	
	
	//模拟考试记录列表
	public function mockList(PaperResultDTO $Paper)
    {
        $resultDO = new ResultDO();

		$identity_id = $Paper->identity_id;
		$pagesize = $Paper->num;
		$page = $Paper->filename['page'];
		$platformId = $Paper->id;

	 try {
		
		$page = ($page-1) * $pagesize;
		$items = 'id,pass_questions,time,is_read,modified,passscore,count(*) num,MAX(modified) score,paperId,paperName,starttime';
        $groupBy = ' group by paperId desc order by id desc  limit '.$page.','.$pagesize;

		$mockexam = new model_newagk_mockexam();
		$platform = new model_newagk_platform();
		$globald = new service_globals();
		//$admin_reg = $platform->getChildAdminRegByPlaformId($platformId);
		$condition = 'identity_id='.$identity_id; // and admin_reg 
		if(!empty($Paper->filename['title'])){
			$condition .= " and paperName like '%".$Paper->filename['title']."%'";
		}

		/**取试卷id  每张试卷最高多少分 和条数**/
		$list = $mockexam->select($condition, $items, $groupBy)->items;
		/**取试卷id  每张试卷最高多少分 和条数 end**/
		
		
		if(empty($list)){
			$resultDO->code = 1;
			$resultDO->message = '没有数据';
			$resultDO->success = true;
            return $resultDO;
			
		}
		$mocklist = [];
		$paperid = [0];
		foreach($list as $v){
			$mocks = $mockexam->selectOne($condition.' and paperId='.$v['paperId'],'modified,passscore,id,starttime,is_read,time,modified,paperId','order by id desc');
			$paperid[] = $v['paperId'];

			if($mocks['is_read']==2){
				$Pass ='未知';
			} else if($mocks['modified']>=$mocks['passscore']){
				$Pass ='合格';
			} else {
				$Pass ='不合格';
			}
			$mocklist[$v['paperId']] = [
							'paperId'	=>$v['paperId'],
							'paperName'=>$v['paperName'],
							'is_read' =>$v['is_read']==2 ? 901 : 0,
							'totalNum'	=>$v['num'],
							'higScore'	=>$v['score'], //最高分
							'passRate'	=>0, //及格率
							'recenPid'	=>$mocks['id'],
							'recenTime'=>date('Y.m.d H:i',$v['starttime']), 
							//'recenTime'=>$mocks['starttime'],//最近一条记录 考试时间
							//'recenCost'=>$globald->secsToStrws($mocks['time']), //最近一条记录 考试用时
							'recenCost'=>$mocks['time'], 
							'recenScore'=>$mocks['is_read']==2 ? '--' : $mocks['modified'], //最近一条记录 分数
							'recenPass'=>$Pass, //最近一条记录 是否合格
							];
		}
		
		/**每张试卷合格数量**/
		$passList = $mockexam->select('identity_id='.$identity_id.' and paperId in('.implode(',',$paperid).') and is_read!=2 and modified>=passscore', 'count(*) num,paperId', 'group by paperId desc')->items;
		/**每张试卷合格数量 end**/
		foreach($passList as $vpass){
			$mocklist[$vpass['paperId']]['passRate'] = ceil(($vpass['num']*100)/$mocklist[$vpass['paperId']]['totalNum']); //floor 
		}

			$resultDO->success = true;
            if ($list){
				$resultDO->data = array_values($mocklist); //去掉key 预防影响取值
				
				$resultDO->code = 1;
            }else{
               $resultDO->code = 0;
            }
			$resultDO->message = 0;
    
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }
	
	//模拟考试记录列表
	public function mockListDetails(PaperResultDTO $Paper)
    {
        $resultDO = new ResultDO();
		$paperid = $Paper->id ? gdl_lib_BaseUtils::getStr($Paper->id,'int') : 0;
		$identity_id = $Paper->identity_id ? gdl_lib_BaseUtils::getStr($Paper->identity_id,'int') : 0;
		$pagesize = $Paper->num ? gdl_lib_BaseUtils::getStr($Paper->num,'int') : 0;
		$page = $Paper->filename['page'] ? gdl_lib_BaseUtils::getStr($Paper->filename['page'],'int') : 0;
	//	$platformId = $Paper->id;

	 try {
		
		$page = ($page-1) * $pagesize;
		$items = 'id,pass_questions,time,is_read,modified,passscore,paperId,paperName,starttime';
        $groupBy = ' order by id desc limit '.$page.','.$pagesize;

		$mockexam = new model_newagk_mockexam();
		$platform = new model_newagk_platform();
		$globald = new service_globals();
		//$admin_reg = $platform->getChildAdminRegByPlaformId($platformId);
		$condition = 'identity_id='.$identity_id.' and paperId='.$paperid; // and admin_reg 


		$list = $mockexam->select($condition, $items, $groupBy)->items;

		$mocklist = [];
		$i=1;
		foreach($list as $v){

			if($v['is_read']==2){
				$Pass ='1';
			} else if($v['modified']>=$v['passscore']){
				$Pass ='2';
			} else {
				$Pass ='3';
			}
			$mocklist[] = [
							'id'	=>$v['id'],
							'number'=>$i,
							'examTime'=>date('Y.m.d H:i',$v['starttime']), // 考试时间
							'cost'=>(int)$v['time'], //考试用时
							'score'=>$v['is_read']==2 ? '--' : $v['modified'], //分数
							'pass'=>$Pass, //是否合格
							];
			$i++;
		}
		
		

			$resultDO->success = true;
            if ($list){
				$resultDO->data = $mocklist;
				$resultDO->code = 1;
            }else{
               $resultDO->code = 0;
            }
			$resultDO->message = 0;
    
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }
	
	//考试中上传答案
	public function record(PaperResultDTO $basic)
    {
		
		$result = new ResultDO();
		$answer = $basic->username ? json_decode($basic->username,true) : [];
		$basicid = $basic->id ? gdl_lib_BaseUtils::getStr($basic->id,'int') : 0;
		$sign = $basic->id ? 1 : 2;
		$identity_id = $basic->identity_id ? gdl_lib_BaseUtils::getStr($basic->identity_id,'int') : 0;
		if(!$identity_id || empty($answer)){
			$result->code = 0;
			$result->message = '缺少必要参数';
			$result->success = true;
            return $result;
			
		}
		
		
	try {

			$examsession = new model_newagk_examsession();
			$globa = new service_globals();
			$ags = $examsession->getListByArgOne('basicid='.$basicid.' and identity_id='.$identity_id.' and sign='.$sign,'es_useranswer,useranswer');
			if(empty($ags)){
				$result->code = 0;
				$result->message = '试卷不存在';
				$result->success = true;
				return $result;
			}
			$es_useranswer = empty($ags['es_useranswer']) ? [] : unserialize($ags['es_useranswer']);
			$useranswer = empty($ags['useranswer']) ? [] : unserialize($ags['useranswer']);
			foreach($answer as $k=>$v){
					$answ = $globa->answSort($v['answer']);
					$es_useranswer[$v['id']] =$answ;
					$useranswer[$v['id']] =$answ;
				
			}

			$examsession->update('basicid='.$basicid.' and identity_id='.$identity_id.' and sign='.$sign,['es_useranswer'=>serialize($es_useranswer),'useranswer'=>serialize($useranswer)]);
			
            $result->code = 1;
			$result->success = true;
            return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
		
	}
	
	
	//模拟考试 考试详情
	public function mockDetails(PaperResultDTO $basic)
    {
		
		$result = new ResultDO();
		$id = $basic->id ? gdl_lib_BaseUtils::getStr($basic->id,'int') : 0;
		$identity_id = $basic->identity_id ? gdl_lib_BaseUtils::getStr($basic->identity_id,'int') : 0;
		if(!$identity_id || !$id){
			$result->code = 0;
			$result->message = '缺少必要参数';
			$result->success = true;
            return $result;
			
		}
		
		
		try {
			$mockexam = new model_newagk_mockexam();
			$globald = new service_globals();
			$collection = new model_newagk_collection();
			$qbank = new model_newagk_qbank();
			$res = $mockexam->getInfoArgOne(['identity_id'=>$identity_id,'id'=>$id],'paperName,question,answer,modified,passscore,starttime,time,is_read,paperId');
			//$logo = $qbank->getListByArgNamefield(0);
			if(empty($res)){
				$result->code = 0;
				$result->success = true;
				$result->message = '记录不存在';
				return $result;
			}
				if($res['is_read']==2){
					$Pass =1;
				} else if($res['modified']>=$res['passscore']){
					$Pass =2;
				} else {
					$Pass =3;
				}

			$collect = $collection->cllKeep($identity_id);
			$datas=[];
			$sheet=[];
			$record=['total'=>0,'done'=>0,'notDone'=>0,'unknown'=>0,'notMade'=>0];
			$question = unserialize($res['question']);
			/*$csanswer = unserialize($res['answer']);
			$answer = [];
			foreach($csanswer as $v){
				$answer[$v[0]['id']] =$v[0]['answer'];
			}*/
			$answer = unserialize($res['answer']);
			$i=1;
			foreach($question as  $k=>$v){

				$record['total'] += count($v);
				foreach($v as  $kq=>$vq){
					$vq["minute"]=(string)$vq["minute"];
					$vq["score"]=(string)$vq["score"];
					$vq['finalAnswer'] = empty($answer[$vq['id']]) ? '' : $answer[$vq['id']]['answer'];
					$vq['collection'] = in_array($vq['id'],$collect) ? 1 : 0;
					//$vq['questionImg'] = empty($logo[$vq['qbankId']]['thumb']) ? '' : $logo[$vq['qbankId']]['thumb'];
		
					if(empty($answer[$vq['id']])){
						$selected =3;//未做0
						//$record['notMade']+=1;
						$record['notDone']+=1;
						$vq['selected'] =3;//未做0
				
					} else {
					
						if($vq['typeId']<4){
							if($vq['answer']==$vq['finalAnswer']){
								$selected =2;//已做对
								$record['done']+=1;
								$vq['selected'] =2;
								
							} else {
								$selected =3;//做错
								$record['notDone']+=1;
								$vq['selected'] =3;
						

							}
						} else {
							$selected =4;//未知
							$vq['selected'] =4;
							$record['unknown']+=1;
							
						}
					}
					//将用户答案丢到题里面去
					$datas[$k][] = $vq;
				//	$sheet[$k][] = ['id'=>$i,'selected'=>$selected]; //答题卡
					
					if(!empty($sheet[$k]['key']) && $sheet[$k]['key']==$k){
						$sheet[$k]['list'][] = ['id'=>$i,'qid'=>$vq['id'],'selected'=>$selected];
					} else {
						$sheet[$k] = ['key'=>$k,'list'=>[['id'=>$i,'qid'=>$vq['id'],'selected'=>$selected]]]; 
					}
					
					$i++;
				}
			}

				$data = [
						'paperName'=>$res['paperName'],
						'modified'=>(string)$res['modified'],
						'examTime'=>date('Y.m.d H:i',$res['starttime']),
						'cost'=>$globald->secsToStr($res['time']),
						'list'=>$datas,
						'sheet'=>array_values($sheet),
						'record'=>$record,
						'pass'=>$Pass,
						
						];

			/**********/
			$result->code = 1;
			$result->success = true;
			$result->message = json_encode($data);
			return $result;
		} catch (Exception $e) {
			$result->success = false;
			$result->code = $e->getCode();
			$result->message = $e->getMessage();
		}
		 return $result;
		
	}
	
	/*****************模拟考试 end********************/
	/***********正式考试*****************/
	//正式考试列表
	public function formalExam(PaperResultDTO $basic)
    {
        $resultDO = new ResultDO();

		$identity_id = $basic->identity_id ? gdl_lib_BaseUtils::getStr($basic->identity_id,'int') : 0;
		$pagesize = $basic->num ? gdl_lib_BaseUtils::getStr($basic->num,'int') : 10;
		$page = $basic->filename['page'] ? gdl_lib_BaseUtils::getStr($basic->filename['page'],'int') : 1;
		$platformId = $basic->id ? gdl_lib_BaseUtils::getStr($basic->id,'int') : 0;
		$basicid = $basic->basicid  ? gdl_lib_BaseUtils::getStr($basic->basicid,'int') : 0;
		
		if(!$identity_id || !$basicid){
			$resultDO->code = 0;
			$resultDO->message = '缺少必要参数';
			$resultDO->success = true;
            return $resultDO;
			
		}
	 try {
		$examsession = new model_newagk_examsession();
		$platform = new model_newagk_platform();
		$paper = new model_newagk_paper();
		$basic = new model_newagk_basic();
		$basicuser = new model_newagk_basicuser();
		$page = ($page-1) * $pagesize;
		$items = $basic->tableName().'.id basicid,b.id,b.name,b.dbs,b.ques_name,b.duration,b.totalScore,b.passScore,b.totalNum,'.$basic->tableName().'.basic,'.$basic->tableName().'.starttime,'.$basic->tableName().'.is_exam,b.puse';
        $groupBy = ' order by '.$basic->tableName().'.id desc  limit '.$page.','.$pagesize;

		$basicid = $basicuser->basicid($identity_id,1);
		$dtime = time();
		$condition = $basic->tableName().".id in({$basicid}) and UNIX_TIMESTAMP(".$basic->tableName().".endtime)>".$dtime.' and '.$basic->tableName().'.status=1 and '.$basic->tableName().'.isdelete=0'; // and admin_reg in('".implode("','",$admin_reg)."')
		
		$leftjoin = array(
            $paper->tableName().' b' => $basic->tableName().'.pid=b.id',
        );
		//$admin_reg = $platform->getChildAdminRegByPlaformId($platformId);


		$sessionvars = $examsession->selectOne('sign=1 and identity_id='.$identity_id,'starttime,time,paperid,papername,basicid');
		$list = $basic->select($condition, $items, $groupBy,"",$leftjoin)->items;

		if(empty($list)){
			$resultDO->code = 1;
			$resultDO->message = '没有找到考试记录';
			$resultDO->success = true;
            return $resultDO;
			
		}

		$mocklist = [];

		$paperid = empty($sessionvars['basicid']) ? 0 : $sessionvars['basicid'];
		$globa = new service_globals();
		foreach($list as $v){
			$starttime = strtotime($v['starttime']);
			$mocklist[] = [
							'id'		=>$v['basicid'],
							'title'		=>htmlspecialchars_decode($v['basic']),
							'qName'		=>$v['ques_name'],
							'pName'		=>$v['name'],
							'mockExam'	=>$v['puse']==2 ? 0 : 1,
							'qId'		=>$v['dbs'],
							'duration'	=>(int)$v['duration'],
							'totalScore'=>$v['totalScore'],
							'passScore'	=>$v['passScore'],
							'totalNum'	=>$v['totalNum'],
							'conExam'	=>$paperid==$v['basicid'] ? 1 : 0,
							'starttime' =>$v['starttime'],
							'examType'	=>$v['is_exam'], //0常规考场，1补考考场
							'startType' =>$starttime>$dtime ? 1 : 0,
							'timeLeft'  =>$starttime>$dtime ? $starttime-$dtime : 0,
							];
		}
		

			$resultDO->success = true;

            if ($list){
				$resultDO->data = $mocklist;
				
				$resultDO->code = 1;
            }else{
               $resultDO->code = 0;
            }
			$resultDO->message =0;
    
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }
	
	//获取当前考场监控规则
	public function regulars(PaperResultDTO $basic)
    {
		$result = new ResultDO();

		$identity_id = $basic->identity_id ? gdl_lib_BaseUtils::getStr($basic->identity_id,'int') : 0;
		$basicid = $basic->basicid ? gdl_lib_BaseUtils::getStr($basic->basicid,'int') : 0;
		if(!$basicid || !$identity_id){
			$result->code = 0;
			$result->message = '缺少必要参数';
			$result->success = true;
            return $result;
			
		}
		try {
				$basic = new model_newagk_basic();
				$basicrule = new model_newagk_basicrule();
				$basicDel = $basic->selectOne(['id'=>$basicid,'status'=>1,'isdelete'=>'0'], 'id,pid,pname,basic,is_exam,monitor,monitorRule,examnumber');

				if(empty($basicDel)){
					$result->code = 0;
					$result->message = '考场不存在';
					$result->success = true;
					return $result;
				}
				$data = [
						'basicName' => $basicDel['basic'], //考场名称
						'is_exam' 	=> $basicDel['is_exam'] ? '补考' : '常规', //考试类型
						'monitor' 	=> $basicDel['monitor'], //是否开启人脸识别 1是启用 0是不启用
						'monitorRule' 	=> $basicDel['monitorRule'],//考前1 考中2考后4 考前+考中3 考前加考后5 考中+考后6 考前+考中+考后7
						'rule' 	=> [['rule'=>'start','num'=>0,'types'=>'','verif'=>0]], //人脸识别规则 规则 random(考试中),start(考试开始),end(考试结束)
						];
				if($basicDel['monitor']){
					$data['rule'] = $basicrule->rule($basicDel['id']);
				}
                if (!empty($data['basicName'])) {
					
					$result->message = json_encode($data);
                    $result->code = 1;

                } else {
                    $result->code = 0;
					$result->message = 0;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
	}
	
	//进入考场前用户确认页面
	public function candInfor(PaperResultDTO $basic)
    {
		$result = new ResultDO();

		$identity_id = $basic->identity_id ? gdl_lib_BaseUtils::getStr($basic->identity_id,'int') : 0;
		$basicid = $basic->basicid ? gdl_lib_BaseUtils::getStr($basic->basicid,'int') : 0;
		if(!$basicid || !$identity_id){
			$result->code = 0;
			$result->message = '缺少必要参数';
			$result->success = true;
            return $result;
			
		}
		try {
				$basic = new model_newagk_basic();
				$paper = new model_newagk_paper();
				$basicuser = new model_newagk_basicuser();
				$basicrule = new model_newagk_basicrule();
				$examspapers = new model_newagk_examspapers();
				$basicDel = $basic->selectOne(['id'=>$basicid,'status'=>1,'isdelete'=>'0'], 'id,pid,pname,basic,is_exam,monitor,monitorRule,examnumber');
				$basicuserDel = $basicuser->selectOne(['basic_id'=>$basicid,'identity_id'=>$identity_id], 'usertruename,idcard');
				$examNum= $examspapers->selectOne(['identity_id'=>$identity_id,'basicid'=>$basicid],'count(*) num');
				if(empty($basicDel) || empty($basicuserDel)){
					$result->code = 0;
					$result->message = '考场不存在';
					$result->success = true;
					return $result;
				}

				$paperDetailed = $paper->selectOne(['id'=>$basicDel['pid']],'totalNum,duration,totalScore,passScore');
				
				$globald = new service_globals();
				$duration = floor($paperDetailed['duration']/60);
				$data = [
						'examnumber'=>$examNum['num']>=$basicDel['examnumber'] ? 1 : 0, //没有考试次数
						'username' 	=> $basicuserDel['usertruename'], //考生姓名
						'idcard' 	=> $basicuserDel['idcard'], //考生身份证号
						'basicName' => $basicDel['basic'], //考场名称
						'pname' 	=> $basicDel['pname'], //试卷名称
						'totalNum' 	=> $paperDetailed['totalNum'], //试题数目
						//'duration' 	=> $globald->secsToStrws($paperDetailed['duration'], //考试时长
						'duration' 	=> (string)$duration,
						'totalScore' 	=> $paperDetailed['totalScore'], //试卷总分
						'passScore'	=> $paperDetailed['passScore'], //及格分数
						'is_exam' 	=> $basicDel['is_exam'] ? '补考' : '常规', //考试类型
						'monitor' 	=> $basicDel['monitor'], //是否开启人脸识别 1是启用 0是不启用
						'monitorRule' 	=> $basicDel['monitorRule'],//考前1 考中2考后4 考前+考中3 考前加考后5 考中+考后6 考前+考中+考后7
						'rule' 	=> [['rule'=>'start','num'=>0,'types'=>'','verif'=>0]], //人脸识别规则 规则 random(考试中),start(考试开始),end(考试结束)
						];
				if($basicDel['monitor']){
					$data['rule'] = $basicrule->rule($basicDel['id']);
				}
                if (!empty($data['username'])) {
					
					$result->message = json_encode($data);
                    $result->code = 1;

                } else {
                    $result->code = 0;
					$result->message = 0;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
	}
	
	
	//考试记录列表
	public function formaList(PaperResultDTO $Paper)
    {
        $resultDO = new ResultDO();

		$identity_id = $Paper->identity_id ? gdl_lib_BaseUtils::getStr($Paper->identity_id,'int') : 0;
		$page = $Paper->filename['page'] ? gdl_lib_BaseUtils::getStr($Paper->filename['page'],'int') : 0;
		$pagesize = $Paper->num ? gdl_lib_BaseUtils::getStr($Paper->num,'int') : 0;
		$title = $Paper->filename['title'] ? gdl_lib_BaseUtils::getStr($Paper->filename['title'],'string') : '';
		$platformId = $Paper->id ? gdl_lib_BaseUtils::getStr($Paper->id,'int') : 0;
		

	 try {
		$platform = new model_newagk_platform();
		$papers = new model_newagk_examspapers();
		$basic = new model_newagk_basic();
		$page = ($page-1) * $pagesize;
		$items = $papers->tableName().'.paperName,'.$papers->tableName().'.starttime,'.$papers->tableName().'.time,'.$papers->tableName().'.is_read,'.$papers->tableName().'.modified,'.$papers->tableName().'.remark,'.$papers->tableName().'.status,'.$papers->tableName().'.type,'.$papers->tableName().'.passscore,'.$papers->tableName().'.basicid,b.basic,b.pname,b.is_exam,b.displayScore,'.$papers->tableName().'.is_read';
        $groupBy = ' order by '.$papers->tableName().'.id desc  limit '.$page.','.$pagesize;
	
		//$admin_reg = $platform->getChildAdminRegByPlaformId($platformId);
		$condition = $papers->tableName().".identity_id=".$identity_id; // and admin_reg in('".implode("','",$admin_reg)."')
		if($title!=''){
			$condition .= " and ( b.basic like '%".$title."%' or  b.pname like '%".$title."%' )";
		}
		$leftjoin = array(
            $basic->tableName().' b' => $papers->tableName().'.basicid=b.id',
        );

	
		$list = $papers->select($condition, $items, $groupBy,'',$leftjoin)->items;
		if(empty($list)){
			$resultDO->code = 1;
			$resultDO->message ='没有考试记录';
            return $resultDO;
		}
		$mocklist = [];
		$globald = new service_globals(); //secsToStrws

		foreach($list as $v){
			$pass = $v['modified']>=$v['passscore'] ? '2' : '3';
			if($v['displayScore']){
				$pass = '1';
				$v['modified']='901';
			} else if($v['is_read']==2){
				$pass = '4';
				$v['modified']='901';
			}
			$mocklist[] = [
							'id'			=>$v['basicid'], //考场id
							'title'			=>$v['basic'], //考场名字
							'starttime'		=>date('Y.m.d H:i',$v['starttime']), //考试时间
							'cost'			=>$globald->secsToStr($v['time']), //考试用时
							'score'			=>$v['modified'], //考试得分
							'remark'		=>$v['remark'], //考试说明
							'auth'		=>$v['type']==3 ? 1 : 0, //身份验证
							'pass'			=>$pass, //考试结果
							'paperName'		=>$v['pname'], //试卷名
							'is_exam'		=>$v['is_exam'] ? '补考' : '正式', //0常规考场，1补考考场
							];
		}
		

			$resultDO->success = true;
			
            if ($list){
				$resultDO->data = $mocklist;
				$resultDO->code = 1;
				
            } else {
               $resultDO->code = 0;
            }
			$resultDO->message = '成功';
    
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }
	/**********正式考试 end*************/
	//考试交卷
	public function carryOut(PaperResultDTO $Paper)
    {
        $resultDO = new ResultDO();

		$basicid = $Paper->basicid;
		$identity_id = $Paper->identity_id;
		$terminal = $Paper->filename['terminal'];
		$answer =$Paper->filename['answer'] ?  json_decode($Paper->filename['answer'],true) : [];
		$status = $Paper->filename['status'];
		$sign = $Paper->basicid ? 1 : 2;
	 try {
		$examsession = new model_newagk_examsession();
		$examspapers = new model_newagk_examspapers();
		$mockexam = new model_newagk_mockexam();
		$basic = new model_newagk_basic();
		$paper = new model_newagk_paper();
		$archivesmark = new model_newagk_archivesmark();
		$usercompany = new model_newagk_usercompany();
		$globa = new service_globals();
		$sessionvars = $examsession->getExamSessionBySessionid($basicid,$identity_id,$sign);
		$usercpy = $usercompany->selectOne(['id'=>$identity_id],'admin_reg');	
		$resultDO->code = 0;
        $resultDO->success = true;
		if (empty($sessionvars)) {
           $resultDO->message = "请勿重复提交试卷，重新考试请重新打开app";
           return $resultDO;
        }
		//$answer = ['65635'=>'B','65622'=>'A']; //临时
		
		if (empty($answer)){
            $answer = unserialize($sessionvars['useranswer']);
        }

				
		/**修改为方便阅卷的格式**/
		$dealWith = [];
		/*foreach($answer as $ku=>$vu){
			if(empty($ku)){
				foreach($vu as $kan=>$van){
					if(!empty($van)){
					$van['answer'] = $globa->answSort($van['answer']);
					$dealWith[$van['id']] = ['answer'=>$van['answer'],'id'=>$van['id']];
					}
				}
				
				
			} else {
				$vu['answer'] = $globa->answSort($vu['answer']);
				$dealWith[$vu['id']] = ['answer'=>$vu['answer'],'id'=>$vu['id']];
			}
		}*/
		
		foreach($answer as $ku=>$vu){
				$vu['answer'] = $globa->answSort($vu['answer']);
				$dealWith[$vu['id']] = ['answer'=>$vu['answer'],'id'=>$vu['id']];
		}
		
		/**修改为方便阅卷的格式 end**/
		
		$scores = $examspapers->scores($sessionvars,$dealWith);// 计算用户的分;

		$basicDetailed = $basic->selectOne(['id'=>$basicid],'displayScore,archiving,admin_reg');
		
		
		$paperDetailed = $paper->selectOne(['id'=>$sessionvars['paperid']],'remark,passScore');
		//$scores['score'] = mt_rand(80,100);
		
		
		$args['answer'] = serialize($dealWith); //用户的答案
		$args['useranswer'] = $sessionvars['useranswer'];
		$args['is_read'] = $scores['especially'];
		$args['terminal'] = $terminal;
		$args['time'] = time()-$sessionvars['starttime'];
		$args['starttime'] = $sessionvars['starttime'];
		$args['modified'] = $args['score'] = $scores['score'];
		$args['question'] = serialize($scores['question']);
		$args['paperId'] = $sessionvars['paperid'];
		$args['paperName'] = $sessionvars['papername'];
		$args['basicid'] = $sessionvars['basicid'];
		$args['type'] = $args['status'] = $status;
		$args['identity_id'] = $sessionvars['identity_id'];
		$args['isvalid'] = $sessionvars['suspicion']!=2 ? 1 : 0;
		$args['remark'] = $paperDetailed['remark'];
		$args['passscore'] = $paperDetailed['passScore'];
		$args['pass_questions'] = $scores['pass'];
		$args['nopass_questions'] = $scores['nopass'];
		$args['reg'] = $usercpy['admin_reg'];
		if($sessionvars['basicid']){
			
			$examNum = $examspapers->selectOne(['basicid'=>$sessionvars['basicid'],'identity_id'=>$sessionvars['identity_id']],'count(*) num');
			$args['remark'] = '第'.($examNum['num']+1).'次考试';
			
			$pid = $examspapers->insert($args);
		} else {
			unset($args['basicid']);
			unset($args['score']);
			$pid = $mockexam->insert($args);
		}
		/////////////////
		$displayScore = $scores['especially']==3 ? $basicDetailed['displayScore'] : 1;
		///////////////
            if ($pid){
				if($basicDetailed['archiving'] && $sessionvars['basicid']){
					$archivesmark->archives($pid); //单人归档
				}
				//$examsession->delete(['identity_id'=>$identity_id,'basicid'=>$basicid]);
				$examsession->delete(['identity_id'=>$identity_id,'sign'=>$sign]); 				//删除临时记录
				$resultDO->data[] = ['displayScore'=>$displayScore,'pid'=>$pid]; 
				$resultDO->message = '交卷成功';
				$resultDO->code = 1;
            } else {
               $resultDO->code = 0;
				$resultDO->message = "交卷失败，确认是否已经交卷";
            }

    
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }
	
	//考试交卷后展示页面
	public function examResults(PaperResultDTO $Paper)
    {
        $resultDO = new ResultDO();

		$basicid = $Paper->basicid ? gdl_lib_BaseUtils::getStr($Paper->basicid) : 0;
		$pid = $Paper->platform_id ? gdl_lib_BaseUtils::getStr($Paper->platform_id) : 0;

	 try {
		
		$mockexam = new model_newagk_mockexam();
		$examspapers = new model_newagk_examspapers();
		$agkpaper = new model_newagk_paper();
		$basic = new model_newagk_basic();
		$globals = new service_globals();
		if($basicid){
			$papers = $examspapers->getInfoArgOne(['id'=>$pid],'is_read,question,answer,passscore,modified,basicid,time,paperId');
			$basicName = $basic->getInfoArgOne(['id'=>$papers['basicid']],'basic,displayScore');
			if (!empty($papers)) {
				
				$papers['paperName'] = $basicName['basic'];
			}
			$displayScore=$basicName['displayScore'] ? 0 : 1;
		} else {
			$papers = $mockexam->getInfoArgOne(['id'=>$pid],'is_read,question,answer,passscore,modified,paperName,time,paperId');
			$displayScore=1;
		}
		
		$resultDO->code = 0;
        $resultDO->success = true;
		if (empty($papers)) {
           $resultDO->message = "数据不存在";
           return $resultDO;
        }
		    
			$settings = $agkpaper->getInfoArgOne(['id'=>$papers['paperId']],'settings');
			$fraction = unserialize($settings['settings']);
			$question = unserialize($papers['question']);
			$answer = unserialize($papers['answer']);
			if(!is_array($answer))	$answer = [];
			$is_read = $papers['is_read'];

			$datas = [
					'stand'=>$papers['modified']>=$papers['passscore'] ? 'stand' : 'failed', //stand 合格 failed 不合格
					'basicName'=>$papers['paperName'],
					'score'=>($is_read==2 || !$displayScore) ? 901 : $papers['modified'], //得分
					'timeCost'=>(string)$globals->secsToStrws($papers['time']), //用时
					'list'=>[],
					'displayScore'=>$displayScore,//1显示分数 0不显示分数
					'pid'=>$papers['paperId'],
					];
			 
			$detailed = $globals->scores($question,$answer,$fraction);
			foreach($detailed as $k=>$v){
				$k = empty($globals->typesf[$k]) ? 'unknown' : $globals->typesf[$k];
				
				$v['types'] = $k;
				//$datas['list'][$k] = $v;
				if($displayScore=='0' || $is_read==2){
					$v['score'] = 901;
					$v['pass'] = 901;
				}
				if(!empty($datas['list'][$k]['key']) && $datas['list'][$k]['key']==$k){
					$datas['list'][$k]['list'][] =  $v;
				} else {
					$datas['list'][$k] = ['key'=>$k,'list'=>[$v]]; 
				}
				
				
				
			}

			$datas['list'] = array_values($datas['list']);
			$resultDO->message = json_encode($datas);
			//$resultDO->data[] = ['displayScore'=>$displayScore,'pid'=>$pid]; 
			//$resultDO->message = '查询成功';
			$resultDO->code = 1;
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }
	
	/*************************************/
	
	/**
     * 获取用户所在考场列表
     * @access public
     * @param int $identity_id
     * @return ResultDO
     */
    public function BasicRoom(PaperRequestDTO $Paper)
    {
        $resultDO = new ResultDO();
        $identity_id =  $Paper->identity_id ? gdl_lib_BaseUtils::getStr($identity_id) : 0;
		$platformid = $Paper->platformid ? gdl_lib_BaseUtils::getStr($Paper->platformid) : 0;
        //$search = gdl_lib_BaseUtils::getStr($search);
      //  $condition = array("identity_id=$identity_id and agk_basic.closed=1");

            $condition = array("agk_basic.closed=1 and agk_basic_user.gdl_userid=$identity_id AND agk_basic_user.platform_id=".$platformid);

        try {
            $modelBasicUser = new model_newagk_basicuser();
            $res = $modelBasicUser->select(
                $condition,
                'agk_basic_user.basic_id basicid,agk_basic.basic,agk_basic.examid,agk_basic_setting.start_time,agk_basic_setting.end_time,agk_basic_setting.paperid,agk_basic_setting.examnumber',
                '',
                'order by agk_basic.id desc',
                array(
                'agk_basic' => 'agk_basic.id = agk_basic_user.basic_id',
                'agk_basic_setting' => 'agk_basic.id = agk_basic_setting.basicid',
                )
                )->items;
           if ($res){
               $resultDO->data = $res;
               $resultDO->code = 1;
           }else{
               $resultDO->code = 0;
           }

            $resultDO->success = true;
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        $resultDO->notify_time = time();
        return $resultDO;
    }
	
	//查询考试次数
	public function getExamUseNumber(PaperRequestDTO $Paper)
    {
        $resultDO = new ResultDO();
		try {
			$identity_id = $Paper->identity_id ? $Paper->identity_id : 0;
			$examid = $Paper->examid ? $Paper->examid : 0;
			$basicid = $Paper->basicid ? $Paper->basicid : 0;
			$type = $Paper->type ? $Paper->type : 0;

			$examspapers = new model_newagk_examspapers();
			$arg = $examspapers->selectOne(['identity_id'=>$identity_id,'ep_paperId'=>$examid,'basicid'=>$basicid,'ep_type'=>$type],' count(*) AS number ');
	  
			$result->data[][] = $arg['number'];
            if ($result) {
                $result->code = 1;
            } else {
                $result->code = 0;
            } 
			
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
		
	}
    //查询考试次数
    public function getExamUseNumber1(PaperRequestDTO $Paper)
    {
        $resultDO = new ResultDO();
        try {
            $identity_id = $Paper->identity_id ? $Paper->identity_id : 0;

            $examspapers = new model_newagk_examspapers();
            $arg = $examspapers->selectOne(['identity_id'=>$identity_id,'ep_paperId'=>$examid,'basicid'=>$basicid,'ep_type'=>$type],' count(*) AS number ');

            $result->data[][] = $arg['number'];
            if ($result) {
                $result->code = 1;
            } else {
                $result->code = 0;
            }

            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;

    }
	
	
	
	//获取用户照片
	public function collect(PaperResultDTO $basic)
    {
		$result = new ResultDO();

		$identity_id = $basic->identity_id ? gdl_lib_BaseUtils::getStr($basic->identity_id,'int') : 0;
	
		if(!$identity_id){
			$result->code = 0;
			$result->message = '缺少必要参数';
			$result->success = true;
            return $result;
			
		}
		try {
				$usercompany = new model_newagk_usercompany();
				$ucentermember = new model_agkuc_ucentermember();
				$photo = $usercompany->selectOne(['id'=>$identity_id],'photoCollect,vface,gdlUserId');
				$member = $ucentermember->selectOne(['id'=>$photo['gdlUserId']],'truename');
				if(empty($photo['photoCollect'])){
					$result->code = 0;
					$result->message = '没有上传留底照片';
					$result->success = true;
					return $result;
				}
				$photo['truename'] = empty($member['truename']) ? '' : $member['truename'];
				$result->message = json_encode($photo);
                $result->code = 1;
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
	}
	
	/*
    *identify 人脸识别
    */
    public function identify(PaperResultDTO $basic)
    {
        $result = new ResultDO();
        //如果对比照片其中一项为空，那么直接返回比对失败
        if(empty($basic->filename['faceImgA'])||empty($basic->filename['faceImgB']))
        {                
            $result->success = true;
            $result->code=2;
            $result->data[0] =  array('similarity' => 0);
            $result->message = 'no img';
            return $result;
        }

        try {

            //今后可设置为全局统一读取配置，利用缓存
             $faceType = gdl_lib_BaseUtils::getStr($basic->filename['faceType'],'int');
            if(!empty($faceType) && $faceType==2) $res = YouTu::facecompareOne($basic->filename['faceImgA'], $basic->filename['faceImgB']);
            elseif(!empty($faceType) && $faceType==1) $res = FaceVisa::facecompareOne($basic->filename['faceImgA'], $basic->filename['faceImgB']);
            else $res = YouTu::facecompareOne($basic->filename['faceImgA'], $basic->filename['faceImgB']);
            //$res = array('msg'=>$res);
            gdl_lib_BaseUtils::addLog(json_encode(['type' => $basic->filename['faceType'],'res' => $res,'data' => $basic]));
            $result->success = true;
            $result->code=2;
            $result->data[0] = $res;
            $result->message = $faceType;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        $result->notify_time = time();
        return $result;
    }

    /**
     * 设置临时session表中 所有超时考试自动交卷 获取答案为字段useranswer
     */
    public function EndExamSession(PaperResultDTO $Paper){
        $resultDO = new ResultDO();
        $time = $Paper->type ? gdl_lib_BaseUtils::getStr($Paper->type,'int') : time();
        try {
            $examsession = new model_newagk_examsession();
            $examspapers = new model_newagk_examspapers();
            $basic = new model_newagk_basic();
            $paper = new model_newagk_paper();
            $archivesmark = new model_newagk_archivesmark();
            $usercompany = new model_newagk_usercompany();

            //查询出所有超时试卷
            $EndBasicLists = $examsession->select(" starttime+time*60<".$time." and sign=1 ","es_id,useranswer,question,setting,suspicion ")->items;
            $p = 0;
            if ($EndBasicLists) {
                foreach ($EndBasicLists as $key=>$sessionvars){
                    $usercpy = $usercompany->selectOne(['id'=>$sessionvars['identity_id']],'admin_reg');
                    $answer = unserialize($sessionvars['useranswer']);

                    $scores = $examspapers->scores($sessionvars,$answer);// 计算用户的分;

                    $basicDetailed = $basic->selectOne(['id'=>$sessionvars['basicid']],'displayScore,archiving,admin_reg');


                    $paperDetailed = $paper->selectOne(['id'=>$sessionvars['paperid']],'remark,passScore');
//                    $scores['score'] = mt_rand(80,100);
                    $dealWith = [];
                    foreach($answer as $v){
                        $dealWith[$v['id']] = $v;
                    }

                    $args['answer'] = serialize($dealWith); //用户的答案
                    $args['useranswer'] = $sessionvars['useranswer'];
                    $args['is_read'] = $scores['especially'];
                    $args['terminal'] = 1;
                    $args['time'] = time()-$sessionvars['starttime'];
                    $args['starttime'] = $sessionvars['starttime'];
                    $args['modified'] = $args['score'] = $scores['score'];
                    $args['question'] = serialize($scores['question']);
                    $args['paperId'] = $sessionvars['paperid'];
                    $args['paperName'] = $sessionvars['papername'];
                    $args['basicid'] = $sessionvars['basicid'];
                    $args['type'] = $args['status'] = 2;
                    $args['identity_id'] = $sessionvars['identity_id'];
                    $args['isvalid'] = $sessionvars['suspicion']!=2 ? 1 : 0;
                    $args['remark'] = $paperDetailed['remark'];
                    $args['passscore'] = $paperDetailed['passScore'];
                    $args['pass_questions'] = $scores['pass'];
                    $args['nopass_questions'] = $scores['nopass'];
                    $args['reg'] = $usercpy['admin_reg'];
                    $pid = $examspapers->insert($args);
                    /////////////////
                    $displayScore = $scores['especially']==3 ? $basicDetailed['displayScore'] : 1;
                    ///////////////
                    if ($pid){
                        $p +=1;
                        if($basicDetailed['archiving'] && $sessionvars['basicid']){
                            $archivesmark->archives($pid); //单人归档
                        }
                        //	$examsession->delete(['identity_id'=>$identity_id,'basicid'=>$basicid]); //删除临时记录
                    }
                }
            }
//            $sessionvars = $examsession->getExamSessionBySessionid($basicid,$identity_id,$sign);
            if ($p>0){
                $resultDO->code =1;
            }else{
                $resultDO->code =0;
                $resultDO->message =json_encode($examsession);
            }
            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = 0;
        }
        return $resultDO;
    }
}
